<template>
  <view>
    <view class="w100 p-all-30" style="padding-top: 2px">
      <uni-card margin="0">
        <view>
          <view class="inforClass"> 任务名称：{{ taskInfo.taskName }}</view>
          <view class="rowsb rowsm mt-20 fs-24">
            <view style="width: 50%">
              <text class="fw-600 fs-26"> 实践课程：</text>
              <text>
                <!-- {{ taskInfo.practiceType == 1 ? '劳动教育' : taskInfo.practiceType == 2 ? '职业素养' :
                  taskInfo.practiceType == 3 ? '应急安全' : taskInfo.practiceType == 4 ? '思政实践' : '创新创业' }} -->
                {{ (typeCongfigList.find(v => v.id == taskInfo.practiceType) || {}).name }}
              </text>
            </view>
            <view style="width: 50%">
              <text class="fw-600 fs-26"> 任务状态：</text>
              <text>{{ taskInfo.taskStatus == 1 ? '未开始' : taskInfo.taskStatus == 2 ? '进行中' : '已结束' }}</text>
            </view>
          </view>
          <view class="rowsb rowsm mt-20 fs-24">
            <view style="width: 50%">
              <text class="fw-600 fs-26"> 积分上限：</text>
              <text>{{ taskInfo.pointsCap }}</text>
            </view>
            <view style="width: 50%" v-if="taskInfo.participationWay == 1">
              <text class="fw-600 fs-26"> 次数：</text>
              <text>{{ performTaskNumber }} / {{ taskInfo.taskNumber }}</text>
            </view>
          </view>
        </view>
        <view class="rowsb rowsm mt-20">
          <view class="ellipsis-text fs-24">
            <text class="fw-600 fs-26"> 发布时间：</text>
            <text>{{ (taskInfo.createTime || '').slice(0, 16) }}</text>
          </view>
        </view>
        <view class="ellipsis-text mt-20 fs-24">
          <text class="fw-600 fs-26"> 任务时间：</text>
          <text>{{ startTime }}~{{ endTime }}</text>
        </view>
        <view class="ellipsis-text mt-10 fs-24">
          <text class="fw-600 fs-26"> 所属学期：</text>
          <text>{{ taskInfo.semesterConfigName }}</text>
        </view>
        <view class="ellipsis-text mt-10" v-if="taskInfo.noPassPoints > 0">
          <text class="fw-600 fs-26"> 如果审核不通过需要扣除 ( {{ taskInfo.noPassPoints }} ) 分</text>
        </view>
      </uni-card>
      <!-- 参与方式 -->
      <uni-card>
        <view class="inforClass"> 参与情况：</view>
        <view class="rowsb rowsm mt-20 fs-24">
          <view style="width: 62%">
            <text class="fw-600 fs-26"> 参与方式：</text>
            <text>
              {{ taskInfo.participationWay == 1 ? '指定学生参与' : '学生自选报名' }}
            </text>
          </view>
          <view style="width: 38%" v-if="taskInfo.participationWay == 2">
            <text class="fw-600 fs-26"> 人数限制：</text>
            <text>{{ taskInfo.applyCount || 0 }} / {{ taskInfo.peoplesNumberAstrict }}</text>
          </view>
        </view>
        <view v-if="taskInfo.participationWay == 2">
          <view class="rowsb rowsm mt-20 fs-24">
            <view class="ellipsis-text" style="width: 62%">
              <text class="fw-600 fs-26"> 报名审核：</text>
              <text>{{ taskInfo.applyCheck == 0 ? '无需审核，直接参与' : '需要审核通过后参与' }}</text>
            </view>
            <view style="width: 38%">
              <text class="fw-600 fs-26"> 学生范围：</text>
              <text> {{ (taskInfo.studentIds || []).length }}</text>
            </view>
          </view>
          <view class="rowsb rowsm mt-20 fs-24">
            <view class="ellipsis-text">
              <text class="fw-600 fs-26"> 报名时间：</text>
              <text>{{ taskInfo.applyStartTime.slice(0, 10) }}~{{ taskInfo.applyEndTime.slice(0, 10) }}</text>
            </view>
            <!-- <view style="width: 38%">
              <text class="fw-600 fs-26"> 报名状态：</text>
              <text>
                {{ taskInfo.applyStatus == 1 ? '报名未开始' : '' }}
              </text>
            </view> -->
          </view>
          <view class="rowsb rowsm mt-20 fs-24">
            <view>
              <text class="fw-600 fs-26"> 报名状态：</text>
              <!-- <text> {{ (applicaStatus.find(v => v.value == taskInfo.participationStatus) || {}).name }}</text> -->
              <text>
                {{ taskInfo.applyStatus == 1 ? '报名未开始' : taskInfo.participationStatus == 0 && taskInfo.applyStatus == 3 ?
                  '报名已结束' : (applicaStatus.find(v => v.value == taskInfo.participationStatus) || {}).name }}
              </text>
            </view>
          </view>
          <view class="rowsb rowsm mt-20 fs-24" v-if="taskInfo.participationStatus == 3 && taskInfo.applyReason">
            <view>
              <text class="fw-600 fs-26"> 报名驳回理由：</text>
              <text> {{ taskInfo.applyReason }} </text>
            </view>
          </view>
          <view class="ellipsis-text mt-15" v-if="taskInfo.applyPassCancelPoints > 0">
            <text class="fw-600 fs-26"> 爽约扣除积分数 ( {{ taskInfo.applyPassCancelPoints }} ) 分</text>
          </view>
        </view>
        <view class="mt-20 fs-24" v-else>
          <text class="fw-600 fs-26"> 学生范围：</text>
          <text> {{ (taskInfo.studentIds || []).length }}</text>
        </view>
      </uni-card>
      <!-- 任务要求 -->
      <uni-card>
        <view class="inforClass"> 任务要求：</view>
        <view class="task-require">{{ taskInfo.taskRequire || '无' }}</view>
      </uni-card>
      <!-- 注意事项 -->
      <uni-card margin="0">
        <view class="inforClass">注意事项：</view>
        <view class="task-require">{{ taskInfo.mattersNeedAttention || '无' }}</view>
      </uni-card>
      <!-- 附件 -->
      <uni-card v-if="taskInfo.fileList && taskInfo.fileList.length > 0">
        <view class="inforClass">附件:</view>
        <view>
          <view v-for="item in taskInfo.fileList" :key="item.id">
            <image :src="item.fileSrc" class="w-200 h-200 br-20"
              v-if="item.fileType == 'png' || item.fileType == 'jpg' || item.fileType == 'jpeg' || item.fileType == 'able' || item.fileType == '图片'"
              mode="aspectFill" @click="openImg(item.fileSrc)">
            </image>
            <video id="myVideo" :src="item.fileSrc" class="w-200 h-200 br-20"
              v-if="item.fileType == 'mp4' || item.fileType == 'avi' || item.fileType == '视频'"
              @click="openVideo(item.fileSrc)"></video>
            <view class="w100 h-140 br-10 rows rowsm pl-40 mb-12" style="background-color: #F7F6FA;"
              v-if="item.fileType != 'png' && item.fileType != 'jpg' && item.fileType != 'jpeg' && item.fileType != 'able' && item.fileType != 'mp4' && item.fileType != 'avi' && item.fileType != '图片' && item.fileType != '视频'"
              @click="openFile(item)">
              <image src="/static/file.png" class="w-60 h-60 mr-20" mode=""></image>
              <view class="fs-28 col888 w100 one_overflow">{{ item.fileName }}</view>
            </view>
          </view>
        </view>
      </uni-card>
      <!-- 按钮 -->
      <view v-if="taskInfo.participationWay == 1">
        <view class="btn" @click="toPage" v-if="taskInfo.taskStatus == 2 && performTaskNumber != taskInfo.taskNumber">
          填报
        </view>
        <view class="btn" style="border: 1px solid #dcdcdc; background: #dcdcdc; color: #a9a9a9" v-else>填报</view>
      </view>
      <view v-else>
        <view class="btn" @click="toPageApply"
          v-if="taskInfo.participationStatus == 0 && taskInfo.taskStatus != 3 && taskInfo.applyStatus == 2">
          报名
        </view>
        <view class="btn" style="border: 1px solid #dcdcdc; background: #dcdcdc; color: #a9a9a9"
          v-if="taskInfo.participationStatus == 1">
          报名审核中
        </view>
        <view class="btn" @click="toPage"
          v-if="taskInfo.taskStatus == 2 && taskInfo.participationStatus == 2 && performTaskNumber != taskInfo.taskNumber">
          填报
        </view>
        <view class="btn" style="border: 1px solid #dcdcdc; background: #dcdcdc; color: #a9a9a9"
          v-if="performTaskNumber == taskInfo.taskNumber && taskInfo.participationStatus == 2">
          填报
        </view>
        <view class="btn" style="border: 1px solid #dcdcdc; background: #dcdcdc; color: #a9a9a9"
          v-if="taskInfo.participationStatus == 3 || (taskInfo.participationStatus == 0 && taskInfo.taskStatus == 3) || (taskInfo.participationStatus == 0 && taskInfo.applyStatus == 3)">
          报名
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import axios from 'axios';
export default {
  data() {
    return {
      taskInfo: {},
      title: '',
      startTime: '',
      endTime: '',
      prozyNameList: [],
      proxyNameList: [],
      probjNameList: [],
      performTaskNumber: 0,
      applicaStatus: [
        { name: '未报名', value: 0 },
        { name: '未审核', value: 1 },
        { name: '已通过', value: 2 },
        { name: '已驳回', value: 3 },
      ],
      practiceTaskUserApplyId: null,
      taskId: null,
      typeCongfigList: []
    };
  },
  onLoad(e) {
    this.title = e.title;
    this.performTaskNumber = e.performTaskNumber;
    this.practiceTaskUserApplyId = e.taskId;
    this.taskId = e.id;
    uni.setNavigationBarTitle({
      title: e.title + '任务详情'
    });
    this.getTypeCongfigList();
    this.getTaskInfo();
  },
  methods: {
    getTypeCongfigList() {
      this.$tools.axiosFromToken('GET', 'project/practice/type/config/listAll', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        this.typeCongfigList = res.rows;
      })
    },
    async fetchImage(urls, index) {
      const that = this;
      try {
        const response = await axios.get(this.$tools.avatarUrl + urls, {
          responseType: 'arraybuffer' // 获取二进制数据
        });
        const blob = new Blob([response.data], { type: 'image/jpeg' });
        const imageUrl = URL.createObjectURL(blob);
        that.taskInfo.fileList[index].fileSrc = imageUrl;
        that.$forceUpdate();
      } catch (error) {
        console.error('Failed to fetch image:', error);
      }
    },
    openImg(url) {
      let urlList = [];
      this.taskInfo.fileList.forEach(item => {
        if (item.fileType == 'jpg' || item.fileType == 'jpeg' || item.fileType == 'png' || item.fileType == 'gif' || item.fileType == 'able' || item.fileType == '图片') {
          urlList.push(item.fileSrc)
        }
      });
      uni.previewImage({
        current: url,
        urls: urlList,
        loop: false,
        indicator: 'number',
      });
      // uni.previewImage({
      //   current: this.$tools.avatarUrl + url,
      //   urls: [this.$tools.avatarUrl + url],
      //   loop: false,
      //   indicator: 'number',
      // });
    },
    openVideo(url) {
      var video = document.getElementById("myVideo");
      // 检查浏览器是否支持全屏 API
      if (video.requestFullscreen) {
        // 支持 requestFullscreen 的浏览器
        video.requestFullscreen();
      } else if (video.mozRequestFullScreen) {
        // Firefox 支持 mozRequestFullScreen
        video.mozRequestFullScreen();
      } else if (video.webkitRequestFullscreen) {
        // Chrome 和 Safari 支持 webkitRequestFullscreen
        video.webkitRequestFullscreen();
      } else if (video.msRequestFullscreen) {
        // Internet Explorer 支持 msRequestFullscreen
        video.msRequestFullscreen();
      }
    },
    openFile(url) {
      const userAgent = navigator.userAgent.toLowerCase();
      if (userAgent.match(/MicroMessenger/i)) {
        const fileUrl = this.$tools.avatarUrl + url.file;
        window.open(fileUrl, '_blank');
      } else if (userAgent.match(/wxwork/i)) {
        const fileUrl = this.$tools.avatarUrl + url.file;
        window.open(fileUrl, '_blank');
      } else {
        const fileUrl = this.$tools.avatarUrl + url.file;
        fetch(fileUrl)
          .then(response => response.blob())
          .then(blob => {
            const link = document.createElement("a");
            link.href = URL.createObjectURL(blob);
            link.download = url.fileName; // 指定下载文件的默认名称
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(link.href); // 释放对象 URL
          })
          .catch(error => {
            console.error("下载失败：", error);
          });
      }
      // uni.downloadFile({
      //   url: this.$tools.avatarUrl + url,
      //   success(res) {
      //     // 获取文件路径
      //     const filePath = res.tempFilePath;
      //     // 在 H5 中，使用浏览器打开文件
      //     uni.openDocument({
      //       filePath: res.tempFilePath,
      //       showMenu: true,
      //       complete(msg) {
      //         console.log(msg)
      //         window.open(filePath, '_blank');
      //       }
      //     })
      //   }
      // })
    },
    getTaskInfo() {
      this.$tools.axiosFromToken('GET', `student/project/task/${this.taskId}/${this.practiceTaskUserApplyId}`, {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        this.taskInfo = { ...res.data };
        this.$nextTick(() => {
          this.taskInfo.fileList.forEach((item, fileIndex) => {
            this.fetchImage(item.file, fileIndex)
          })
        })
        this.startTime = this.taskInfo.startTime.slice(0, 10);
        this.endTime = this.taskInfo.endTime.slice(0, 10);
        // if (this.taskInfo.faceZy) {
        //   this.getListProxy();
        //   this.getListProzy();
        //   this.getListProbj();
        // };
      })
    },
    toPage() {
      if (this.taskInfo.isSubmit == '已完成' || this.taskInfo.isSubmit == '审核中') {
        this.$tools.goNext(`/pagesCopy/submitWork/weekWorkDetail?title=${this.title}&id=${this.taskInfo.id}&taskName=${this.taskInfo.taskName}`)
      } else {
        this.$tools.goNext(`/pagesCopy/submitWork/weekWork?title=${this.title}&id=${this.taskInfo.id}&taskName=${this.taskInfo.taskName}`)
      }
      // uni.navigateTo({
      //   url:'/pagesCopy/submitWork/weekWork?title=' + this.title
      // })
    },
    toPageApply() {

      uni.showModal({
        title: `确认`,
        content: `是否确认报名该任务？`,
        success: (res) => {
          if (res.confirm) {
            this.$tools.axiosFromToken('PUT', `project/apply`, { practiceTaskId: this.taskInfo.id, id: this.practiceTaskUserApplyId }, '加载中').then(res => {
              if (res.code != 200) return this.$tools.showtt(res.msg)
              this.$tools.showtt('报名成功');
              this.getTaskInfo();
            })
          } else if (res.cancel) {
            // 用户点击了“取消”
            console.log('取消');
          }
        }
      });
    },

    // 查询学院
    getListProxy() {
      this.$tools.axiosFromToken('GET', 'project/proxy/listTotalAll', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        this.proxyNameList = [];
        res.rows.forEach(v => {
          this.taskInfo.faceXy.split(',').forEach(y => {
            if (v.id == y) {
              this.proxyNameList.push(v.name)
            }
          })
        })
      })
    },

    getListProzy() {
      this.$tools.axiosFromToken('GET', 'project/prozy/listTotalAll', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        this.prozyNameList = [];
        res.rows.forEach(v => {
          this.taskInfo.faceZy.split(',').forEach(y => {
            if (v.id == y) {
              this.prozyNameList.push(v.name)
            }
          })
        })
      })
    },
    getListProbj() {
      this.$tools.axiosFromToken('GET', 'project/probj/listTotalAll', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        this.probjNameList = [];
        res.rows.forEach(v => {
          this.taskInfo.faceBj.split(',').forEach(y => {
            if (v.id == y) {
              this.probjNameList.push(v.name)
            }
          })
        })
      })
    },

  }
}
</script>

<style lang="scss">
page {
  background-color: #fff;
}

::v-deep .uni-card {
  margin-left: 5px !important;
  margin-right: 5px !important;
  overflow: visible;
}

::v-deep .uni-card__content {
  color: #000 !important;
}

::v-deep .uni-tooltip {
  width: 50%;
  display: flex;
}

::v-deep .uni-tooltip-popup {
  top: 20px;
  right: 0;
  text-align: justify;
  word-wrap: break-word;
}

.inforClass {
  font-size: 16px;
  font-weight: 700;
  display: flex;
  align-items: center;
  margin: 8px 0;
}

.inforClass::before {
  content: '';
  width: 5px;
  height: 20px;
  background-color: #007AFF;
  margin-right: 5px;
  display: inline-block;
}

.mark {
  text-align: right;
  color: #f92929;
}

.txt-warp {
  display: flex;
  justify-content: space-between;
  margin-top: 30rpx;

  .left,
  .center,
  .right {
    text {
      display: block;
      white-space: nowrap;
      font-size: 24rpx;
      color: #333;
      margin-bottom: 20rpx;
    }
  }
}

.txt {
  font-size: 24rpx;
  color: #333;
}

.title {
  font-size: 30rpx;
  color: #333;
  font-weight: bold;
  margin-top: 30rpx;
}

.task-require {
  margin-top: 30rpx;
  border: 1px solid #c2bfbf;
  padding: 20rpx;
  border-radius: 10rpx;

  .title {
    font-size: 30rpx;
    color: #333;
    font-weight: bold;
    margin-top: 10rpx;
  }

  .txt {
    font-size: 24rpx;
    color: #4e4e4e;
    margin-top: 10rpx;
  }
}

::v-deep .uni-tooltip {
  width: 50%;
  display: flex;
}

.ellipsis-text {
  white-space: nowrap;
  /* 不允许换行 */
  overflow: hidden;
  /* 隐藏溢出的部分 */
  text-overflow: ellipsis;
  /* 超出部分显示省略号 */
  width: 100%;
  /* 或者根据需要设置一个固定宽度 */
  display: inline-block;
  /* 或者使用 block，取决于你的布局需求 */
}

.btn {
  margin: 0 auto;
  margin-top: 50px;
  width: 300px;
  font-size: 26rpx;
  border: 1px solid #4897FF;
  padding: 10px 20px;
  border-radius: 20px;
  text-align: center;
  color: #fff;
  background: linear-gradient(to bottom, #4897FF, #4878FF)
}
</style>
